/**
 * Created by Administrator on 2017/5/24 0024.
 */
require(["jquery","paging","template","bootstrap","echarts","bbcare","scprit/department/view/template/follow-up/common.js"],function($,Paging,template,bootstrap,echarts,$bb,$common) {
    var URL = $bb.baseUrl("department")+"followup/service";
    var obj=$bb.getPageParams();
    var userId=obj.babyId;
    var type=obj.type;//历史记录传参；
    var count =1, pagesize=16;
    'use strict';
    var arr = new Array();
    var allPostion;
    var months =  [1, 2, 3 , 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 18, 21, 24, 27, 30, 33, 36, 42, 48, 54, 60, 66, 72, 78, 84];
    getBabyInfo();
    getAllPostion();
    $common.date();
    var btnSubmit= $("#submitData");
    $(".mask, .AddInformation").hide();
    $("#historyData").click(function(event) {
        getBabyHistoryList(1, pagesize);
        var p = new Paging();
        $("#pageTool").html("");
        p.init({target:'#pageTool',pagesize:pagesize,count:count,toolbar:false,callback:function(page,size,count){
            getBabyHistoryList(page,size);
        }});
        $(".mask, .AddInformation").show();
    });
    $(".AddInformation h4 span").click(function(event) {
        $(".mask, .AddInformation").hide();
    });
    var account=eval('('+sessionStorage.account+')');
    var accountName=account.alias;
    $("#userName").html(accountName);//检查医生名字
    $("#nowTime").html($common.getNowFormatDate());
    //婴儿信息：
    function getBabyInfo() {
        $bb.ajax({
            url: URL+"/patient/patientInfoPtId",
            data: JSON.stringify({
                data: {
                    "patientId":userId
                }
            }),
            success: function (data) {
                if(data.success) {
                    var babyInfo=data.data.PatientInfo;
                    var babyData=$common.babyInfoDeal(babyInfo);
                    $common.infoInit({"id":"#babyInfoList","data":babyData});
                    btnSubmit.removeAttr("disabled");
                    //提交测试
                    btnSubmit.click(function(){
                        $bb.ajax({
                            url: URL+"/patient/evaluation/getScore",
                            data: JSON.stringify({
                                data: {
                                    "userId" : userId,
                                    "examinationPaperName" : type,
                                    "postionIds" : JSON.stringify(arr)
                                }
                            }),
                            success: function (data) {
                                if(data.success) {
                                    localStorage.setItem("Neuropsychology",JSON.stringify(data.data));
                                    $bb.openPage("childPsychologyResult",obj);
                                } else {
                                    $bb.toastShow("获取数据失败!");
                                }
                            }
                        });
                    });
                } else {
                    $bb.toastShow("患者信息获取失败！",1500);
                    btnSubmit.click(function(){
                        $bb.toastShow("患者信息不全,无法提交测试！",1500);
                        $(this).attr("disabled","true");
                    });
                }
            }
        });
    }
    function getAllPostion() {
        $bb.ajax({
            url: URL+"/patient/evaluation/getAllPostion",
            async: false,
            data: JSON.stringify({
                data: {
                    "examinationPaperName" : type,//评测类型；
                    "userId":userId
                }
            }),
            success: function (data) {console.log(data);
                if(data.success) {
                    allPostion = data.data;
                    showPostion(allPostion, 1);
                }
            }
        });
    }

    $.tabs = {
        init: function() {
            this.orgData = months;//s数据源
            this.showNumber = 8; //每组显示X条数据
            this.groupIndex = 0;  //当前租索引
            this.initStyle();
        },
        bind: function() {
            var _this = this;
            $(".tabs-ul li[group]").click(function() { //绑定分组的单击事件
                var group = $(this).attr("group");
                if(group == "prev") {
                    if(_this.groupIndex >0){
                        _this.groupIndex --;
                        _this.initStyle();
                    }
                } else if(group == "next") {
                    var maxGroupIndex = _this.orgData.length/_this.showNumber;
                    if(_this.orgData.length % _this.showNumber != 0){
                        maxGroupIndex = parseInt(_this.orgData.length/_this.showNumber) + 1;
                    }
                    maxGroupIndex --;
                    if(_this.groupIndex < maxGroupIndex){
                        _this.groupIndex ++;
                        _this.initStyle();
                    }
                }
            });
            $(".tabs-ul li[item]").click(function() {
                var index = parseInt($(this).attr("item"));
                $(".tabs-ul li[item]").removeClass("active");
                $(this).addClass("active");
                showPostion(allPostion, months[index]);
            });
        },
        initStyle: function (itemIndex){
            var _this = this, data = _this.orgData, showNumber = _this.showNumber, count = data.length,
                groupIndex = _this.groupIndex, start = 0, end = 0, str = '<li group="prev"><a href="javascript:;">《</a></li>';
            start = groupIndex * showNumber;
            end = (groupIndex + 1) * showNumber;
            end > count?(end = count):'';
            for(var i=start; i< end; i++){
                var cls  = ' class=';
                if(i == start || i == itemIndex){
                    cls += '"active" ';
                }
                str += '<li item="'+ i +'" '+ cls +'><a href="javascript:;">'+ data[i] +'月智龄</a><i></i></li>';
            }
            str += '<li group="next"><a href="javascript:;">》</a></li>';
            $(".tabs-ul").html(str);
            this.bind();
            showPostion(allPostion, months[start]);
        },
        changeTabs: function(index) {
        }
    };
    $.tabs.init();
    function showPostion(allPostion, num) {
        var one, two, three, four, five;
        for(var i=0;i<months.length;i++){
            if(months[i]==num){
                if(num<3) {one=months[0];two=months[1];three=months[2];four=months[3];five=months[4];}
                else if(num>72){one=months[months.length-5];two=months[months.length-4];three=months[months.length-3];four=months[months.length-2];five=months[months.length-1];}
                else {one=months[i-2];two=months[i-1];three=months[i];four=months[i+1];five=months[i+2];}
            }
        }

        var title ='<th>能区/智龄</th><th>'+one+'月智龄</th><th>'+two+'月智龄</th><th>'+three+'月智龄</th><th>'+four+'月智龄</th><th>'+five+'月智龄</th>';
        $("#showTitle").html(title);

        var bigMovementTab = '<tr>'+'<td>大运动</td>';
        var fineActionTab = '<tr>'+'<td>精细动作</td>';
        var adaptabilityTab = '<tr>'+'<td>适应能力</td>';
        var languageTab = '<tr>'+'<td>语言</td>';
        var socialBehaviorTab = '<tr>'+'<td>社交行为</td>';

        $.each(allPostion, function(index,content) {
            var month = index;
            if(month==one || month==two || month==three || month==four || month==five) {
                var params = {
                    month : month,
                    bigMovement    : content.bigMovement,
                    fineAction     : content.fineAction,
                    adaptability   : content.adaptability,
                    language 	   : content.language,
                    socialBehavior : content.socialBehavior
                };
                bigMovementTab +='<td>';
                for(var i=0;i<params.bigMovement.length;i++) {
                    bigMovementTab +='<div style="height:'+80/params.bigMovement.length+'px" tp="slect" class="td-chd" id="'+params.bigMovement[i].id+'">'+params.bigMovement[i].name+'</div>';
                }
                bigMovementTab +='</td>';

                fineActionTab +='<td>';
                for(var i=0;i<params.fineAction.length;i++) {
                    fineActionTab +='<div style="height:'+80/params.fineAction.length+'px" tp="slect" class="td-chd" id="'+params.fineAction[i].id+'">'+params.fineAction[i].name+'</div>';
                }
                fineActionTab +='</td>';

                adaptabilityTab +='<td>';
                for(var i=0;i<params.adaptability.length;i++) {
                    adaptabilityTab +='<div style="height:'+80/params.adaptability.length+'px" tp="slect" class="td-chd" id="'+params.adaptability[i].id+'">'+params.adaptability[i].name+'</div>';
                }
                adaptabilityTab +='</td>';

                languageTab +='<td>';
                for(var i=0;i<params.language.length;i++) {
                    languageTab +='<div style="height:'+80/params.language.length+'px" tp="slect" class="td-chd" id="'+params.language[i].id+'">'+params.language[i].name+'</div>';
                }
                languageTab +='</td>';

                socialBehaviorTab +='<td>';
                for(var i=0;i<params.socialBehavior.length;i++) {
                    socialBehaviorTab +='<div style="height:'+80/params.socialBehavior.length+'px" tp="slect" class="td-chd" id="'+params.socialBehavior[i].id+'">'+params.socialBehavior[i].name+'</div>';
                }
                socialBehaviorTab +='</td>';
            }
        });
        bigMovementTab += '</tr>';
        fineActionTab += '</tr>';
        adaptabilityTab += '</tr>';
        languageTab += '</tr>';
        socialBehaviorTab += '</tr>';
        $("#showPostion").html(bigMovementTab+fineActionTab+adaptabilityTab+languageTab+socialBehaviorTab);

        setTableStyle(num);
    }
    function setTableStyle(num) {
        //添加问题选中样式
        for(var i=0;i<arr.length;i++){
            $("#"+arr[i]).addClass("active");
        }
        $(".postiontable tr [tp=slect]").click(function() {
            if($(this).hasClass("active")){
                $(this).removeClass("active");
                $common.removeByValue(arr, $(this).attr("id"));
            } else {
                $(this).addClass("active");
                arr.push($(this).attr("id"));
            }
        });
        var index = 4;
        if(num == 1) index=2;if(num == 2) index=3;if(num == 78) index=5;if(num == 84) index=6;
        $(".postiontable tr th:nth-child("+index+")").each(function(){//循环table的每行（tr）
            $(this).css({"background":"#2ab5c7","color": "#FFF"});
        });
    }

    //历史记录：
    var HashMap=$common.hashmap(),hashMap = new HashMap();
    $("#dataList").on('click',"ul[result]",function () {
        var data = eval("("+hashMap.get($(this).attr("result")).replace(/\=/g,"\:")+")");
        localStorage.setItem("Neuropsychology",JSON.stringify(data));
        $bb.openPage("childPsychologyResult",obj);
    });

    function getBabyHistoryList(page, rows) {
        $bb.ajax({
            url: URL+"/patient/evaluation/getHistoryScore",//baby地址
            async: false,
            data: JSON.stringify({
                data: {
                    "userId": userId,
                    "examinationPaperName": type,
                    "page": page,
                    "rows": rows
                }
            }),
            success: function (data) {
                if (data.success) {
                    hashMap = new HashMap();
                    count = data.total;
                    var babyData=data.rows;
                    if(count==0){
                        $bb.toastShow("患者还未参与该项测评！",1500);
                    }
                    var str = '';
                    for (var i = 0; i < data.rows.length; i++) {
                        hashMap.put(data.rows[i].answerId, data.rows[i].result);
                        var pretermBirth = 37 * 7 > data.rows[i].pregnancyWeek ? "是" : "否";
                        var nowDate =$common.getNowFormatDate();
                        var monthAge = $common.DateDiff(nowDate, data.rows[i].birthday) / 30;
                        var weight= data.rows[i].birthWeight==undefined?"未知":data.rows[i].birthWeight+"(g)";
                        var doctorName= data.rows[i].doctorName==undefined?"未知":data.rows[i].doctorName;

                        str += '<ul class="clearfix" result="' + data.rows[i].answerId + '">';
                        str += '<li>' + data.rows[i].babyName + '</li>';
                        str += '<li>' + weight+ '</li>';
                        str += '<li>' + data.rows[i].birthday + '</li>';
                        str += '<li>' + data.rows[i].pregnancyWeek + '(天)</li>';
                        str += '<li>' + pretermBirth + '</li>';
                        str += '<li>' + doctorName + '</li>';
                        str += '<li>' + data.rows[i].createTime + '</li>';
                        str += '</ul>';
                    }
                    $("#dataList").html(str);
                }
            }
        });
    }

});